﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Data.Linq;
using System.Net;
using System.Xml;

namespace SacNetUG.Models
{
    public class DataContextWrapper<T> : IDataContextWrapper where T : DataContext, new()
    {
        private readonly T _db;
        private bool _disposed;

        public DataContextWrapper()
        {
            var t = typeof(T);
            _db = (T)Activator.CreateInstance(t);
        }

        public DataContextWrapper(string connectionString)
        {
            var t = typeof(T);
            _db = (T)Activator.CreateInstance(t, connectionString);
        }

        #region IDataContextWrapper Members

        /// <summary>
        /// Tables this instance.
        /// </summary>
        /// <typeparam name="TTableName"></typeparam>
        /// <returns></returns>
        //public List<TTableName> Table<TTableName>() where TTableName : class
        public IQueryable<TTableName> Table<TTableName>() where TTableName : class
        {
            var table = (Table<TTableName>)_db.GetTable(typeof(TTableName));

            //return table.ToList();
            return table.AsQueryable();
        }

        public void DeleteAllOnSubmit<TEntity>(IEnumerable<TEntity> entities) where TEntity : class
        {
            _db.GetTable(typeof(TEntity)).DeleteAllOnSubmit(entities);
        }

        public void DeleteOnSubmit<TEntity>(TEntity entity) where TEntity : class
        {
            _db.GetTable(typeof(TEntity)).DeleteOnSubmit(entity);
        }

        public void InsertOnSubmit<TEntity>(TEntity entity) where TEntity : class
        {
            _db.GetTable(typeof(TEntity)).InsertOnSubmit(entity);
        }

        public void SubmitChanges()
        {
            _db.SubmitChanges();
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        #endregion

        /// <summary>
        /// Releases unmanaged and - optionally - managed resources
        /// </summary>
        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
        private void Dispose(bool disposing)
        {
            if (_disposed)
                return;

            if (disposing)
            {
                _db.Dispose();
            }

            _disposed = true;
        }
    }
}